﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CMSModel;

public partial class new_edit : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bd();
        }
    }
    void bd()
    {
        int id = Convert.ToInt32(Request["id"]);
        CMSModel.CMSEntities dal = DAL.DBManager.GetCmsEmtity();
        CMSModel.News news = dal.News.First(x => x.id == id);
        if (!string.IsNullOrEmpty(news.ImageUrl))
        {
            Image1.ImageUrl = news.ImageUrl;
        }
        else
        {
            Image1.Visible = false;
        }
        txtNewsId.Text = news.id.ToString();
        txtTitle.Text = news.title;
        txtContent.Text = news.content;
        txtKeyWords.Text = news.keyword;
        txtStock.Text = news.Stock;
        txtAuthor.Text = news.author;
        txtSummary.Text = news.Summary;
        txtSource.Text = news.Source;
        txtOutsideUrl.Text = news.OutsideUrl;
        ddlNature.SelectedValue = Convert.ToString(news.Nature);
        txtPTime.Text = news.ptime == null ? "" : news.ptime.Value.ToString("yyyy-MM-dd HH:mm");
        if (news.IsEnable == true)
            rdoEnableYes.Checked = true;
        else
            rdoEnableNo.Checked = true;
        var types = dal.News_Type.Where(x => x.NewsId == id);
        foreach (var n in types)
        {
            hidNewType.Value += n.NewsTypeId.ToString() + ",";
            lblSelectType.Text += dal.NewsType.First(x => x.id == n.NewsTypeId).name + ",";
        }
        if (lblSelectType.Text != "")
        {
            hidSelectValue.Value += hidNewType.Value.Substring(0, hidNewType.Value.Length - 1);
            lblSelectType.Text = lblSelectType.Text.Substring(0, lblSelectType.Text.Length - 1);
        }
        DataList1.DataSource = dal.NewsType.Where(x => x.pid == null);
        DataList1.DataBind();

    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        int id = Convert.ToInt32(Request["id"]);
        CMSModel.CMSEntities dal = DAL.DBManager.GetCmsEmtity();
        CMSModel.News news = dal.News.First(x => x.id == id);
        news.ImageUrl = Image1.ImageUrl;
        news.author = txtAuthor.Text;
        news.content = txtContent.Text;
        news.keyword = txtKeyWords.Text;
        news.title = txtTitle.Text;
        news.Summary = txtSummary.Text;
        news.Stock = txtStock.Text;
        news.Source = txtSource.Text;
        news.step = int.Parse(ddlStep.SelectedValue);
        news.Nature = int.Parse(ddlNature.SelectedValue);
        if (!string.IsNullOrEmpty(txtPTime.Text))
        {
            news.ptime = DateTime.Parse(txtPTime.Text);
        }
        news.OutsideUrl = txtOutsideUrl.Text;
        if (rdoEnableYes.Checked)
        {
            news.IsEnable = true;
            if (news.ptime == null)
            {
                news.ptime = DateTime.Now;
            }
        }
        else
            news.IsEnable = false;
        news.ctime = news.ctime;
        try
        {
            var list = dal.News_Type.Where(x => x.NewsId == id);
            foreach (var n in list)
            {
                dal.News_Type.DeleteObject(n);
            }
            dal.SaveChanges();
            string str = hidSelectValue.Value;

            //删除相关股票
            var stocks = dal.NewsRelatedStocks.Where(x => x.NewsId == news.id);
            foreach (var c in stocks)
            {
                dal.NewsRelatedStocks.DeleteObject(c);
            }

            //添加相关股票
            if (!string.IsNullOrEmpty(txtStock.Text))
            {
                string[] cc = txtStock.Text.Split(',', '，');
                foreach (var c in cc)
                {
                    NewsRelatedStocks s = new NewsRelatedStocks();
                    s.NewsId = news.id;
                    s.Stock = c;
                    try
                    {
                        s.StockName = CommonBll.DicStocks[s.Stock];
                    }
                    catch
                    {
                    }
                    dal.NewsRelatedStocks.AddObject(s);
                }
            }
            if (str != "")
            {
                foreach (var c in str.Split(','))
                {
                    news.News_Type.Add(new CMSModel.News_Type() { ctime = DateTime.Now, News = news, NewsTypeId = c });
                }
                dal.SaveChanges();
                CacheClearBLL.NewsClear(news.id);
                ClientScript.RegisterStartupScript(GetType(), "aa", "alert('修改成功');document.location='default.aspx?newsTypeId=" + Request["newsTypeId"] + "&page=" + Request["page"] + "'", true);
            }
            else
            {
                ClientScript.RegisterStartupScript(GetType(), "aa", "alert('未选择新闻类型');", true);
            }

        }
        catch (Exception ex)
        {
            LogYuMin.LogWriter.GetWriter(LogYuMin.LogFile.error).Write(GetType(), "EditNews", LogYuMin.LogStates.ERROR, ex);
            ClientScript.RegisterStartupScript(GetType(), "aa", "alert('修改失败')", true);
        }
    }
    protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        int id = Convert.ToInt32(Request["id"]);
        var newstype = (NewsType_NewsTypeSelect)e.Item.FindControl("NewsTypeSelect1");
        newstype.BindData(id);
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx?newsTypeId=" + Request["newsTypeId"] + "&page=" + Request["page"]);
    }

    protected void Button3_Click(object sender, EventArgs e)
    {
        string imageUrl = null;
        if (FileUpload1.HasFile)
        {
            var data = FileUpload1.FileBytes;
            var fileName = FileUpload1.FileName;
            FileBLL fileBLL = new FileBLL();
            imageUrl = fileBLL.UpNewsImage(data, fileName);
            Image1.Visible = true;
            Image1.ImageUrl = imageUrl;
        }
    }
}